import { setObject } from '@app-nextmesh/common/utils';
import { showLoading } from '@app-nextmesh/components';
import { documentV2 } from '@app-nextmesh/domain';
import { useProjectStore } from '@app-nextmesh/store/project';
import { useEffect, useState } from 'react';
import BaseForm from '../../BaseForm';
import { IProps } from '../types';

export default function VisualizationForm({
  data: initData,
  requestType,
  onClose,
  onUpdateTitle,
  onUpdate,
}: IProps) {
  const [data, setData] = useState({ ...initData.formData });
  const projectInfo = useProjectStore((state) => state.projectInfo);
  useEffect(() => {
    const formData = { ...initData.formData };
    if (!formData.items) {
      formData.items = {};
    }
    setData(formData);
  }, [initData]);
  const handleOk = async (data: any) => {
    const hide = showLoading();
    try {
      let request: Promise<any>;
      if (requestType === 'add') {
        request = documentV2.addPostprocess(data);
      } else if (requestType === 'update') {
        request = documentV2.updatePostprocess(data);
      }
      const rspData = await request;
      onUpdate(rspData);
      onClose();
    } catch (error) {
      console.error(error);
    } finally {
      hide();
    }
  };
  const handleInputChange = (name: string, value: string) => {
    const newData = { ...data };
    if (name === 'name' && requestType === 'update') {
      // 更新标题
      onUpdateTitle?.(value);
    }
    setObject(newData, name, value);
    setData(newData);
  };
  function handleClose() {
    if (requestType === 'update') {
      // 重置label
      onUpdateTitle?.(initData.formData.name);
    }
    onClose();
  }
  return (
    <BaseForm
      disabled={projectInfo.readonly}
      title={data.name}
      onClose={handleClose}
      onOk={async () => await handleOk(data)}
      updateTitle={(title) => handleInputChange('name', title)}></BaseForm>
  );
}
